{% extends "base.html" %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h3 mb-0 text-gray-800">{{ api.name }}</h1>
        <p class="mb-0 text-muted">ID: {{ api.id }} | Created: {{ api.created_at }}</p>
    </div>
    <div class="d-flex gap-2">
        <a href="/api/{{ api.id }}/edit" class="btn btn-primary">
            <i class="bi bi-pencil me-1"></i> Edit
        </a>

        <a href="/api/{{ api.id }}/export" class="btn btn-outline-success">
            <i class="bi bi-download me-1"></i> Export
        </a>
        <form action="/api/{{ api.id }}/delete" method="post" class="d-inline">
            <button type="submit" class="btn btn-danger">
                <i class="bi bi-trash me-1"></i> Delete
            </button>
        </form>
    </div>
</div>

{% if api.description %}
<div class="alert alert-info mb-4">
    {{ api.description }}
</div>
{% endif %}

{% if api.get('load_error') %}
<div class="alert alert-danger mb-4">
    <strong>Script Load Error:</strong> {{ api.load_error }}
    <p class="mt-2">Please edit the API and fix the script.</p>
</div>
{% endif %}

<div class="row mb-4">
    <div class="col-lg-8">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">API Endpoints</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Function</th>
                                <th>Endpoint</th>
                                <th>Description</th>
                                <th>Test</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% if api.functions and api.functions|length > 0 %}
                                {% for func_name, func in api.functions.items() %}
                                <tr>
                                    <td><code>{{ func_name }}</code></td>
                                    <td>
                                        <div>
                                            <code>POST {{ func.endpoint }}</code>
                                            {% if func.custom_path %}
                                            <span class="badge bg-success ms-2">Custom</span>
                                            {% else %}
                                            <span class="badge bg-info ms-2">Default</span>
                                            {% endif %}
                                        </div>
                                        <small class="text-muted">
                                            {% if func.custom_path %}
                                            Default: <code>{{ func.default_path }}</code>
                                            {% endif %}
                                        </small>
                                    </td>
                                    <td>{{ func.description }}</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary test-endpoint"
                                                data-endpoint="{{ func.endpoint }}"
                                                data-func-name="{{ func_name }}">
                                            <i class="bi bi-lightning"></i> 测试
                                        </button>
                                    </td>
                                </tr>
                                {% endfor %}
                            {% else %}
                                <tr>
                                    <td colspan="4" class="text-center py-4">
                                        <div class="text-muted">
                                            <i class="bi bi-exclamation-circle fs-1"></i>
                                            <h5 class="mt-3">No Functions Found</h5>
                                            <p>Make sure your script defines functions (not starting with underscore).</p>
                                            <p>Common reasons:</p>
                                            <ul class="text-start">
                                                <li>Script contains syntax errors</li>
                                                <li>Functions are defined inside classes or other functions</li>
                                                <li>Function names start with _ (underscore)</li>
                                            </ul>
                                        </div>
                                    </td>
                                </tr>
                            {% endif %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">Python Script</h6>
                <div>
                    <button class="btn btn-sm btn-outline-secondary" id="copyScriptBtn">
                        <i class="bi bi-clipboard me-1"></i> Copy
                    </button>
                    <button class="btn btn-sm btn-outline-primary" data-bs-toggle="collapse" data-bs-target="#scriptCollapse">
                        <i class="bi bi-arrows-expand me-1"></i> Expand
                    </button>
                </div>
            </div>
            <div class="collapse show" id="scriptCollapse">
                <div class="card-body p-0">
                    <pre class="m-0"><code class="language-python">{{ script_content }}</code></pre>
                </div>
            </div>
        </div>
    </div>
    
     <div class="col-lg-4">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">API Security</h6>
                <form action="/api/{{ api.id }}/toggle_auth" method="post" class="d-inline">
                    <button type="submit" class="btn btn-sm {% if api.auth_required %}btn-outline-danger{% else %}btn-outline-success{% endif %}">
                        {% if api.auth_required %}
                            <i class="bi bi-shield-lock me-1"></i> Disable Auth
                        {% else %}
                            <i class="bi bi-shield me-1"></i> Enable Auth
                        {% endif %}
                    </button>
                </form>
            </div>
            <div class="card-body">
                <div class="mb-4">
                    <h6 class="font-weight-bold">Authentication</h6>
                    <div class="d-flex align-items-center mb-3">
                        <span class="badge bg-{% if api.auth_required %}success{% else %}warning{% endif %} me-2">
                            {% if api.auth_required %}Enabled{% else %}Disabled{% endif %}
                        </span>
                        <span>
                            {% if api.auth_required %}
                                API key required for access
                            {% else %}
                                Open access (no API key needed)
                            {% endif %}
                        </span>
                    </div>
                    
                    <!-- API密钥部分 -->
                    {% if api.auth_required %}
                    <h6 class="font-weight-bold mt-4">API Key</h6>
                    <div class="api-key-container">
                        <div class="api-key-value" id="apiKeyValue">
                            {{ api.api_key }}
                        </div>
                        <div class="d-flex justify-content-between mt-3">
                            <button class="btn btn-sm btn-outline-primary" 
                                    onclick="copyToClipboard('{{ api.api_key }}', this)">
                                <i class="bi bi-clipboard me-1"></i> Copy Key
                            </button>
                            <form action="/api/{{ api.id }}/regenerate_key" method="post" class="d-inline">
                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                    <i class="bi bi-arrow-repeat me-1"></i> Regenerate
                                </button>
                            </form>
                        </div>
                    </div>
                    <div class="alert alert-warning mt-3">
                        <i class="bi bi-exclamation-triangle me-1"></i> 
                        Keep this key secret. Anyone with this key can access your API endpoints.
                    </div>
                    {% else %}
                    <div class="alert alert-info mt-4">
                        <i class="bi bi-info-circle me-1"></i>
                        This API is publicly accessible. No API key is required for access.
                    </div>
                    {% endif %}
                </div>
                
                <div class="mb-3">
                    <h6 class="font-weight-bold">Usage Instructions</h6>
                    {% if api.auth_required %}
                    <p>To call this API, include the following header in your requests:</p>
                    <pre class="bg-light p-2 rounded">X-API-Key: {{ api.api_key }}</pre>
                    {% else %}
                    <p>This API does not require authentication. Simply send requests to the endpoints.</p>
                    {% endif %}
                    
                    <p class="mb-0">Example using curl:</p>
                    <pre class="bg-light p-2 rounded">curl -X POST \
  -H "Content-Type: application/json" \
  {% if api.auth_required %}-H "X-API-Key: {{ api.api_key }}" {% endif %}\
  -d '{"param1": "value1", "param2": "value2"}' \
  "{% if api.functions and func %}{{ func.endpoint }}{% else %}YOUR_ENDPOINT{% endif %}"</pre>
                </div>
            </div>
        </div>
        
        <div class="card shadow">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">API Information</h6>
            </div>
            <div class="card-body">
                <ul class="list-group list-group-flush">
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>API Prefix</span>
                        <span class="text-muted">{{ api_prefix }}</span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Created At</span>
                        <span class="text-muted">{{ api.created_at }}</span>
                    </li>
                    {% if api.updated_at %}
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Last Updated</span>
                        <span class="text-muted">{{ api.updated_at }}</span>
                    </li>
                    {% endif %}
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Status</span>
                        <span class="badge bg-success">Active</span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Functions</span>
                        <span class="badge bg-primary">{{ api.functions|length }}</span>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- Test Modal -->
<div class="modal fade" id="testModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Test API Endpoint: <span id="modalFuncName"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Endpoint URL</label>
                    <input type="text" id="endpointUrl" class="form-control" readonly>
                </div>

                <!-- 修改为JWT令牌输入 -->
                <div class="mb-3">
                    <label class="form-label">JWT Token</label>
                    <div class="input-group">
                        <input type="text" id="jwtTokenInput" class="form-control"
                               placeholder="Enter JWT token">
                        <button class="btn btn-outline-primary" type="button"
                                onclick="openTokenWindow()">
                            <i class="bi bi-key"></i> 获取 Token
                        </button>
                    </div>
                    <div class="form-text">
                        <a href="/get_token" target="_blank" id="tokenLink">在新窗口中获取 Token</a>
                    </div>
                </div>

                <div class="mb-3">
                    <label class="form-label">Request Parameters (JSON)</label>
                    <textarea id="requestParams" class="form-control" rows="5"
                              placeholder='{"param1": "value1", "param2": "value2"}'></textarea>
                    <div class="form-text">Enter parameters as JSON object</div>
                </div>

                <div class="d-grid mb-3">
                    <button id="sendRequestBtn" class="btn btn-primary">
                        <i class="bi bi-send me-1"></i> Send Request
                    </button>
                </div>

                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h6 class="mb-0">Response</h6>
                        <small>Status: <span id="responseStatus" class="badge bg-secondary">Pending</span></small>
                    </div>
                    <div class="card-body p-0">
                        <pre id="responseOutput" class="p-3 mb-0" style="min-height: 200px; max-height: 400px; overflow: auto;">Waiting for request...</pre>
                    </div>
                    <div class="card-footer d-flex justify-content-between">
                        <small>Executed by: <span id="executedBy">-</span></small>
                        <small>Time: <span id="responseTime">-</span></small>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 防止重复初始化
    let modalInitialized = false;
    let currentModal = null;

    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM loaded, initializing test buttons...');

        // 测试端点按钮
        const testButtons = document.querySelectorAll('.test-endpoint');
        console.log('Found', testButtons.length, 'test buttons');

        testButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                console.log('Test button clicked');
                const endpoint = this.dataset.endpoint;
                const funcName = this.dataset.funcName;

                console.log('Endpoint:', endpoint, 'Function:', funcName);

                document.getElementById('endpointUrl').value = endpoint;
                document.getElementById('modalFuncName').textContent = funcName;

                // 清空响应区域
                document.getElementById('responseOutput').textContent = 'Waiting for request...';
                document.getElementById('responseStatus').textContent = 'Pending';
                document.getElementById('responseStatus').className = 'badge bg-secondary';
                document.getElementById('responseTime').textContent = '-';
                document.getElementById('executedBy').textContent = '-';

                // 显示模态框
                const modalElement = document.getElementById('testModal');
                if (modalElement) {
                    // 如果已经初始化过，直接显示
                    if (modalInitialized && currentModal) {
                        currentModal.show();
                    } else {
                        // 否则创建新的模态框实例
                        currentModal = new bootstrap.Modal(modalElement);
                        currentModal.show();
                        modalInitialized = true;
                    }
                } else {
                    console.error('Modal element not found');
                }
            });
        });

        // 发送请求按钮 - 只绑定一次
        const sendRequestBtn = document.getElementById('sendRequestBtn');
        if (sendRequestBtn && !sendRequestBtn.hasListener) {
            sendRequestBtn.hasListener = true;
            sendRequestBtn.addEventListener('click', sendRequestHandler);
        }

        // 添加获取令牌的函数
        window.getToken = function() {
            window.open('/login', '_blank');
        };
    });

    // 打开获取 Token 的窗口
    function openTokenWindow() {
        window.open('/get_token', 'tokenWindow', 'width=600,height=500');
    }

    // 监听来自 Token 窗口的消息
    window.addEventListener('message', function(event) {
        if (event.data.type === 'token_generated') {
            document.getElementById('jwtTokenInput').value = event.data.token;

            // 如果模态框未打开，则打开它
            if (currentModal && !document.getElementById('testModal').classList.contains('show')) {
                currentModal.show();
            }
        }
    });

    // 发送请求的处理函数
    function sendRequestHandler() {
        console.log('Send request button clicked');

        const endpoint = document.getElementById('endpointUrl').value;
        const jwtToken = document.getElementById('jwtTokenInput').value;
        const paramsText = document.getElementById('requestParams').value;
        const outputEl = document.getElementById('responseOutput');
        const statusEl = document.getElementById('responseStatus');
        const timeEl = document.getElementById('responseTime');
        const executedByEl = document.getElementById('executedBy');

        outputEl.textContent = 'Sending request...';
        statusEl.textContent = 'Processing';
        statusEl.className = 'badge bg-info';

        const startTime = Date.now();

        try {
            // 尝试解析JSON参数
            const params = paramsText ? JSON.parse(paramsText) : {};

            // 设置请求头
            const headers = {
                'Content-Type': 'application/json'
            };

            // 如果有JWT令牌，添加到请求头
            if (jwtToken) {
                headers['Authorization'] = 'Bearer ' + jwtToken;
            }

            // 发送POST请求
            axios.post(endpoint, params, {
                headers: headers
            })
            .then(response => {
                const endTime = Date.now();
                const duration = endTime - startTime;

                outputEl.textContent = JSON.stringify(response.data, null, 2);
                statusEl.textContent = 'Success';
                statusEl.className = 'badge bg-success';
                timeEl.textContent = `${duration}ms`;

                if (response.data && response.data.executed_by) {
                    executedByEl.textContent = response.data.executed_by;
                }
            })
            .catch(error => {
                const endTime = Date.now();
                const duration = endTime - startTime;

                if (error.response) {
                    outputEl.textContent = JSON.stringify(error.response.data, null, 2);
                    statusEl.textContent = `Error ${error.response.status}`;
                } else {
                    outputEl.textContent = 'Error: ' + error.message;
                    statusEl.textContent = 'Error';
                }
                statusEl.className = 'badge bg-danger';
                timeEl.textContent = `${duration}ms`;
            });
        } catch (e) {
            const endTime = Date.now();
            const duration = endTime - startTime;

            outputEl.textContent = 'Invalid JSON: ' + e.message;
            statusEl.textContent = 'Error';
            statusEl.className = 'badge bg-danger';
            timeEl.textContent = `${duration}ms`;
        }
    }

    // 确保模态框关闭按钮正常工作
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('btn-close') ||
            e.target.getAttribute('data-bs-dismiss') === 'modal' ||
            (e.target.classList.contains('btn') && e.target.getAttribute('data-bs-dismiss') === 'modal')) {
            if (currentModal) {
                currentModal.hide();
            }
        }
    });
</script>
{% endblock %}